package jupitermouse.site.sink.custom.mysql.test;

import jupitermouse.site.sink.custom.mysql.MysqlSinkFunction;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

import java.util.stream.Stream;

/**
 * wc 统计的数据来自socket
 */
@Slf4j
public class Sink2MysqlStreamingWCJavaApp {

    public static void main(String[] args) throws Exception {

        //获取参数
        int port = 9999;
        try{
            ParameterTool tool = ParameterTool.fromArgs(args);
            port = tool.getInt("port");
        }catch (Exception e){
            log.info("参数未设置，默认为9999");
        }

        //获取环境
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //读取数据
        DataStreamSource<String> source = env.socketTextStream("localhost", port);

        //转换操作
        SingleOutputStreamOperator<Tuple2<String, Long>> operator = source.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] values = value.toLowerCase().split(" ");
                Stream.of(values)
                        .forEach(item -> {
                            collector.collect(new Tuple2<>(item, 1L));
                        });
            }
        }).keyBy(0)
                .timeWindow(Time.seconds(5))
                .sum(1);
        operator.print().setParallelism(1);
        operator.addSink(new MysqlSinkFunction());

        env.execute("StreamingWCJavaApp");

    }
}
